﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Revit.Electric.Common;

namespace HYRElectric.Equipment
{
	public class RandomLayout : EquipmentLayout
	{
		public RandomLayout(UIDocument uiDoc, Document document, DbFamilyObject familyObject, FamilySymbol selectedFamilySymbol, List<BuiltInCategory> lstFilter) : base(uiDoc, document, familyObject, selectedFamilySymbol, lstFilter)
		{
		}

		public override bool Layout()
		{
			if (!base.Layout())
			{
				return false;
			}
			Transaction transaction = null;
			try
			{
				List<ElementId> elements = this.GetElements();
				this.PromptForFamilyInstancePlacement(this.familySymbol);
				List<ElementId> elements2 = this.GetElements();
				List<ElementId> list = new List<ElementId>();
				foreach (ElementId item in elements2)
				{
					if (!elements.Contains(item))
					{
						list.Add(item);
					}
				}
				transaction = new Transaction(this.doc, "RandomLayout");
				transaction.Start();
				foreach (ElementId id in list)
				{
					base.SetParametersValue(id, this.dbFamilyObject.Size);
				}
				transaction.Commit();
			}
			catch (Exception ex)
			{
				if (transaction != null && transaction.GetStatus() != TransactionStatus.Committed)
				{
					transaction.RollBack();
				}
				TaskDialog.Show("盈建科提示", ex.Message);
				return false;
			}
			return true;
		}

		private bool PromptForFamilyInstancePlacement(FamilySymbol jigType)
		{
			bool result;
			try
			{
				this.docUI.PromptForFamilyInstancePlacement(jigType);
				result = true;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private List<ElementId> GetElements()
		{
			List<ElementId> list = new List<ElementId>();
			foreach (BuiltInCategory builtInCategory in this.categoryFilters)
			{
				List<ElementId> collection = new FilteredElementCollector(this.doc).OfCategory(builtInCategory).OfClass(typeof(FamilyInstance)).ToElementIds().ToList<ElementId>();
				list.AddRange(collection);
			}
			return list;
		}
	}
}
